package fr.persistence.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import fr.persistence.GenericDao;

@Repository
public class GenericDaoImpl<T, K extends Serializable> 
	implements GenericDao<T, K> {
 
    private Class<T> type;

    @Autowired
	private SessionFactory sessionFactory;
 
    public GenericDaoImpl() {}

    public GenericDaoImpl(Class<T> type) {
        this.type = type;
    }


	public boolean createObject(T o) {
		sessionFactory.getCurrentSession().save(o);
		return true;
    }
 
    @SuppressWarnings("unchecked")
	public T readObject(K id) {
    	return (T) sessionFactory.getCurrentSession().get(type, id);
    }
 
    @SuppressWarnings("unchecked")
	public List<T> readAllObject() {
    	Criteria crit = sessionFactory.getCurrentSession().createCriteria(type);
    	return crit.list();
    }
 
    public boolean updateObject(T o) {
		sessionFactory.getCurrentSession().update(o);
		return true;
    }
 
    public boolean deleteObject(T o) {
		sessionFactory.getCurrentSession().delete(o);
		return true;
    }
  
}
